package com.gxuwz.restaurant.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.restaurant.common.Result;
import com.gxuwz.restaurant.entity.User;
import com.gxuwz.restaurant.mapper.UserMapper;
import com.gxuwz.restaurant.utils.SaltUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UseController {
   @Resource
    UserMapper userMapper;


   @PostMapping("/login")//post用来新增
  public Result<?> login(@RequestBody User user, HttpServletRequest request){
      //获取主体对象
       Subject subject = SecurityUtils.getSubject();
  try {
      QueryWrapper<User> queryWrapper =  new QueryWrapper<>();
      queryWrapper.eq("username",user.getUsername());
      User user1 = userMapper.selectOne(queryWrapper);
        if(user1==null){
            return Result.error("1","用户名错误");
        }
     if (user1.getRole().equals(user.getRole())){

         HttpSession session = request.getSession(true);
         session.setAttribute("user", user.getUsername());  //将登陆者信息存入session
         session.setAttribute("role", user.getRole());
         UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
         subject.login(token);
         return Result.success(user1);
     }else {
         return Result.error("1","用户身份选择错误");
     }
  }catch (UnknownAccountException e){
      System.out.println("用户名错");

  }catch (IncorrectCredentialsException e){
      System.out.println("密码错");
  }
  return Result.error("1","用户名或密码错误");
    }

    //注册

    @PostMapping ("/register")
    public Result<?> register(@RequestBody User user){


        User olduser = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
      if(olduser!=null){
          System.out.println("用户名重复");
            return Result.error("1","用户名已存在");
        }else {
//========================密码md5加密============================
          //生成随机盐
          String  salt = SaltUtil.getSalt(8);
          //将随机盐保存到数据
          user.setSalt(salt);
          //将明文密码进行md5+salt+hash散列
          Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
          user.setPassword(md5Hash.toHex());
//===============================================
         user.setRole("未激活");//注册默认身份是店员

  user.setAvatar("http://localhost:9480/files/d8fac9c663194127ab5f4967752f5c11");
          System.out.println("执行注册");
          userMapper.insert(user);

          return Result.success();
      }



    }


    @PostMapping //post用来新增
    public Result<?> save(@RequestBody User user){
        System.out.println("执行添加");
        System.out.println(user);
        if(user.getPassword() == null){
//========================密码md5加密================
            //生成随机盐
            String  salt = SaltUtil.getSalt(8);
            //将随机盐保存到数据
            user.setSalt(salt);
            //将明文密码进行md5+salt+hash散列
            user.setPassword("123456");
            Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
            user.setPassword(md5Hash.toHex());
//===============================================

        }
        userMapper.insert(user);

        return Result.success();
      }
    @DeleteMapping("/{id}") //DELETE用来删除
    public Result<?> delete(@PathVariable long id){
        System.out.println("执行删除方法");
        userMapper.deleteById(id);

        return Result.success();


    }

    @PutMapping //put用来更新
    public Result<?> update(@RequestBody User user){
        System.out.println("执行更新"+user.getPassword());
        QueryWrapper<User> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("id",user.getId());

if(user.getPassword().equals(userMapper.selectOne(queryWrapper).getPassword()) ){
    userMapper.updateById(user);
    return Result.success();
}else {
    //========================密码md5加密============
    //生成随机盐
    String  salt = SaltUtil.getSalt(8);
    //将随机盐保存到数据
    user.setSalt(salt);
    //将明文密码进行md5+salt+hash散列

    Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
    user.setPassword(md5Hash.toHex());
//===============================================
    userMapper.updateById(user);
    return Result.success();
}






    }
    //修改密码
    @PutMapping ("/Restorepassword")//put用来更新
    public Result<?> editpassword(@RequestBody User user){
       System.out.println("执行恢复密码");
        System.out.println(user+"拿到的对象值");





//========================密码md5加密============================
        //生成随机盐
        String  salt = SaltUtil.getSalt(8);
        //将随机盐保存到数据
        user.setSalt(salt);
        //将明文密码进行md5+salt+hash散列

        Md5Hash md5Hash = new Md5Hash("123456",salt,1024);
        user.setPassword(md5Hash.toHex());
//===============================================
        userMapper.updateById(user);



        return Result.success();


    }



    @GetMapping("/select")   //get用来查询
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize,
                           @RequestParam(defaultValue = "") String search){
        System.out.println("执行查询");
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(User::getNickname,search);
        }

       Page<User> userPage =  userMapper.selectPage(new Page<>(pageNum,pageSize), wrapper);


       return Result.success(userPage );


    }




    @GetMapping("/loginOut")//post用来新增
    public Result<?> loginOut(){
        System.out.println("调用退出登录，清除认证信息");
        //获取主体对象
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
       return Result.success();
    }




}
